﻿/*
 * Created by SharpDevelop.
 * User: Corrado Mio
 * Date: 27/06/2012
 * Time: 09:57
 * 
 * 
 */
using System;
using System.Reflection;
using System.Threading;

namespace CSharpExt.Threading
{
    /// <summary>
    /// Description of ThreadUtils.
    /// </summary>
    public static class ThreadUtils
    {
        /// <summary>
        /// Ricupera il 'threadId' di Windows del thread corrent
        /// </summary>
        /// <returns></returns>
        [System.Runtime.InteropServices.DllImport("Kernel32")]
        public static extern Int32 GetCurrentThreadId();
        
        /// <summary>
        /// Compone il nome del thread a partire da un template e dal metodo
        /// passato come argomento
        /// </summary>
        /// <param name="n">eventuale nome gia' presente</param>
        /// <param name="format"></param>
        /// <param name="callback"></param>
        /// <returns></returns>
        public static String ComposeName(String n, String format, Action callback)
        {
            if (String.IsNullOrEmpty(n))
            {
                MethodInfo mi = callback.Method;
                n = String.Format(format, mi.DeclaringType.Name, mi.Name);
            }
            
            if (n.StartsWith("."))
            {
                n = Thread.CurrentThread.Name + n;
            }
            return n;
        }
        
        /// <summary>
        /// Compone il nome del thread a partire da un template e dal metodo
        /// passato come argomento
        /// </summary>
        /// <param name="n">eventuale nome gia' presente</param>
        /// <param name="format"></param>
        /// <param name="callback"></param>
        /// <returns></returns>
        public static String ComposeName(String n, String format, Action<Object> callback)
        {
            if (String.IsNullOrEmpty(n))
            {
                MethodInfo mi = callback.Method;
                n = String.Format(format, mi.DeclaringType.Name, mi.Name);
            }
            
            if (n.StartsWith("."))
            {
                n = Thread.CurrentThread.Name + n;
            }
            return n;
        }
        
        
        public static String ComposeName(String n, String format, Runnable runnable)
        {
            if (String.IsNullOrEmpty(n))
            {
                n = String.Format(format, runnable.GetType().FullName);
            }
            
            if (n.StartsWith("."))
                n = Thread.CurrentThread.Name + n;
            return n;
        }
        
        
        public static void CallRunnable(Object runnable)
        {
            ((Runnable)runnable).Run();
        }
    }
}
